package 智能邮件测试;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

public class H5MimeUtil {
	private static Session session;
	private static Logger log = Logger.getLogger(H5MimeUtil.class);

	static {
		// 发送邮件的环境属性
		final Properties props = new Properties();

		props.setProperty("mail.transport.protocol", "smtp");

		props.setProperty("mail.host", "smtp.139.com");

		props.setProperty("mail.smtp.auth", "true");// 请求身份认证

		session = Session.getInstance(props);
	}

	public static MimeMessage newMimeMessage(String fromUser, String sendToUser, String personal, String ccUser,
			String bccUser, InputStream in, List<String> params)
			throws MessagingException, UnsupportedEncodingException {

		MimeMessage message = null;

		if (null != in) {
			message = new MimeMessage(session, in);
		} else {
			message = new MimeMessage(session);
		}

		if (null != fromUser) {
			// 设置发件人
			InternetAddress iaformUser = new InternetAddress(fromUser, personal, "utf-8");
			message.setFrom(iaformUser);
		}

		if (null != sendToUser) {
			// 设置收件人
			InternetAddress iatoUser = new InternetAddress(sendToUser);
			message.setRecipient(RecipientType.TO, iatoUser);
		} else if (null == in && null == sendToUser) {
			throw new MessagingException("501 Invalid Address");
		}
		if (null != ccUser) {
			// 设置抄送
			InternetAddress iaccUser = new InternetAddress(ccUser);
			message.setRecipient(RecipientType.CC, iaccUser);
		}
		if (null != bccUser) {
			// 设置密送，其他的收件人不能看到密送的邮件地址
			InternetAddress iabccUser = new InternetAddress(bccUser);
			message.setRecipient(RecipientType.BCC, iabccUser);
		}

		StringBuilder sb = new StringBuilder();

		if (params != null && params.size() > 0) {
			sb.append("店名").append(":").append(params.get(0)).append(";").append("公司名").append(":")
					.append(params.get(1)).append(";").append("商品").append(":").append(params.get(2)).append(";")
					.append("金额").append(":").append(params.get(3)).append(";").append("url").append(":")
					.append(params.get(4)).append(";");
			System.out.println(sb.toString());
		}

		byte[] encodeBase64 = Base64.encodeBase64(sb.toString().getBytes("utf-8"));
		String BASE64 = new String(encodeBase64, "utf-8");

		message.setHeader("X-RICHINFO-IN", "MSUMMARY:" + BASE64);
		return message;
	}

	public static MimeMessage setFileToMimeMessage(MimeMessage message, File file, String filename)
			throws MessagingException, IOException {

		Object o = message.getContent();
		if (o instanceof Multipart) {
			Multipart multipart = (Multipart) o;
			BodyPart attachmentBodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(file);
			attachmentBodyPart.setDataHandler(new DataHandler(source));
			attachmentBodyPart.setFileName(MimeUtility.encodeWord(filename));
			multipart.addBodyPart(attachmentBodyPart);
			message.setContent(multipart);
		}
		return message;
	}

	/**
	 * 判断此邮件是否包含附件
	 */
	public boolean isContainAttach(Part part) throws Exception {
		boolean attachflag = false;
		// String contentType = part.getContentType();
		if (part.isMimeType("multipart/*")) {
			Multipart mp = (Multipart) part.getContent();
			for (int i = 0; i < mp.getCount(); i++) {
				BodyPart mpart = mp.getBodyPart(i);
				String disposition = mpart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE))))
					attachflag = true;
				else if (mpart.isMimeType("multipart/*")) {
					attachflag = isContainAttach((Part) mpart);
				} else {
					String contype = mpart.getContentType();
					if (contype.toLowerCase().indexOf("application") != -1)
						attachflag = true;
					if (contype.toLowerCase().indexOf("name") != -1)
						attachflag = true;
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			attachflag = isContainAttach((Part) part.getContent());
		}
		return attachflag;
	}

	/**
	 * 保存附件
	 */
	public void saveAttachMent(Part part, String firstDir, String secondDir, String fileName) throws Exception {
		// String fileName = "";
		if (part.isMimeType("multipart/*")) {
			Multipart mp = (Multipart) part.getContent();
			for (int i = 0; i < mp.getCount(); i++) {
				BodyPart mpart = mp.getBodyPart(i);
				String disposition = mpart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
					// fileName = mpart.getFileName();
					// if (fileName.toLowerCase().indexOf("gb2312") != -1) {
					// fileName = MimeUtility.decodeText(fileName);
					// }
					saveFile(fileName, firstDir, secondDir, mpart.getInputStream());
				} else if (mpart.isMimeType("multipart/*")) {
					saveAttachMent(mpart, firstDir, secondDir, fileName);
				} else {
					fileName = mpart.getFileName();
					if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
						fileName = MimeUtility.decodeText(fileName);
						saveFile(fileName, firstDir, secondDir, mpart.getInputStream());
					}
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			saveAttachMent((Part) part.getContent(), firstDir, secondDir, fileName);
		}
	}

	/**
	 * 保存附件到指定目录里
	 */
	public void saveFile(String fileName, String firstDir, String secondDir, InputStream in) throws Exception {
		String osName = System.getProperty("os.name");
		String storedir = "";
		String separator = "";
		if (osName == null)
			osName = "";
		if (osName.toLowerCase().indexOf("win") != -1) {
			separator = "\\";
			if (storedir == null || storedir.equals(""))
				storedir = "D:\\" + firstDir + separator + secondDir;
		} else {
			separator = "/";
			storedir = "/home/cloudlinkin/biz/PDF/" + firstDir + separator + secondDir;
		}

		File storefile = new File(storedir + separator + fileName);
		// 获取文件的文件夹
		File dirs = storefile.getParentFile();
		if (!dirs.exists()) {
			dirs.mkdirs();
		}
		storefile.createNewFile();
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(storefile));
			bis = new BufferedInputStream(in);
			int c;
			while ((c = bis.read()) != -1) {
				bos.write(c);
				bos.flush();
			}
		} catch (Exception exception) {
			log.error("文件保存失败:" + storefile.getPath());
		} finally {
			bos.close();
			bis.close();
		}
	}

	/**
	 * 测试
	 * 
	 * @Description: TODO
	 * @param args
	 * @throws Exception
	 * @return: void
	 */
	// public static void main(String args[]) throws Exception {
	// File file = new File("d:\\DZFP\\ceshi.eml");
	// FileInputStream in = new FileInputStream(file);
	// byte[] buff = new byte[in.available()];
	// in.read(buff);
	//
	// String mimeTemp = new String(buff, "utf-8");
	//
	// InputStream is = new ByteArrayInputStream(mimeTemp.getBytes("UTF-8"));
	// MimeMessage mime = MimeUtil.newMimeMessage(null, null, null, null, is);
	//
	// System.out.println(new MimeUtil().isContainAttach(mime));
	// String first = new
	// SimpleDateFormat("yyyyMMddHH").format(System.currentTimeMillis());
	// String second = new
	// SimpleDateFormat("mm").format(System.currentTimeMillis());
	// new MimeUtil().saveAttachMent(mime, first, second, "123456.pdf");
	//
	// }

}
